home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 4038 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  2.2 KB

  1. Path: news.th-darmstadt.de!news!enno
  2. From: enno@inferenzsysteme.informatik.th-darmstadt.de (Enno Sandner)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Template casting problem
  5. Date: 27 Jan 1996 12:36:45 GMT
  6. Organization: Fachbereich Informatik, TH Darmstadt
  7. Distribution: world
  8. Message-ID: <ENNO.96Jan27133645@kitz.inferenzsysteme.informatik.th-darmstadt.de>
  9. References: <41@site73.site73.ping.at>
  10. NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
  11. In-reply-to: mgeramb@site73.site73.ping.at's message of Thu, 25 Jan 1996 08:48:52 GMT
  12.  
  13. In article <41@site73.site73.ping.at> mgeramb@site73.site73.ping.at (Michael Geramb) writes:
  14.  
  15.    Here is a C++ problem that I never managed to solve.
  16.  
  17.    Imagine you create a template of a class :
  18.  
  19.    template <class T> class A
  20.    {
  21.        ...
  22.    };
  23.  
  24.    This gives a family of classes (instances), say:
  25.  
  26.    A<short>, A<int>, A<float> etc, which may coexist in one function.
  27.    Then, a problem arises how to cast one instance to another.
  28.  
  29.    As a more concrete example, one may imagine a template CVector which
  30.    generates short, integer, float and double instances. 
  31.    It also generates a very natural (to my mind) wish to cast 
  32.    one instance to another.
  33.  
  34. It's possible (at least in theory) to provide a templated conversion
  35. operator:
  36.     
  37.     template<class S> class A {
  38.         ...
  39.        template<class T> operator A<T>() const;
  40.         ...
  41.     };
  42.  
  43. However the todays compilers will reject this code. In the meantime
  44. an auxilary generic function should do the job. If 'A' is an array
  45. class with overloaded 'operator []' and a member-function 'Length'
  46. the appropriate function may look like:
  47.  
  48.     template<class S,class T> A<T> Convert(const A<S>& source) {
  49.            A<T> target(source.Length());
  50.        for (int i=0; i<source.Length(); i++)
  51.         target[i]=(T)source[i];
  52.            return target;
  53.     }
  54.  
  55. This function requieres that objects of type S could be converted to
  56. objects type T. If S is not a builtin type you have to provide an
  57. appropriate conversion operator. Thus compared to the former solution
  58. it's not possible to convert e.g. 'an array of an array of floats' to
  59. 'an array of an array of ints'. I think an implementation that uses
  60. template-specialization can remove this restriction.
  61.  
  62.     Enno
  63.